package org.dalmatian.app.auth.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import org.dalmatian.app.auth.service.IAuthStrategy;
import org.dalmatian.app.auth.service.SysLoginService;
import org.dalmatian.app.auth.service.SysRegisterService;
import org.dalmatian.app.system.domain.bo.SysTenantBo;
import org.dalmatian.app.system.domain.vo.SysClientVo;
import org.dalmatian.app.system.domain.vo.SysTenantVo;
import org.dalmatian.app.system.service.ISysClientService;
import org.dalmatian.app.system.service.ISysConfigService;
import org.dalmatian.app.system.service.ISysSocialService;
import org.dalmatian.app.system.service.ISysTenantService;
import org.dalmatian.common.core.constants.Constants;
import org.dalmatian.common.core.constants.GlobalConstants;
import org.dalmatian.common.core.constants.SystemConstants;
import org.dalmatian.common.core.domain.R;
import org.dalmatian.common.core.domain.model.LoginBody;
import org.dalmatian.common.core.utils.JsonUtils;
import org.dalmatian.common.core.utils.MapstructUtils;
import org.dalmatian.common.core.utils.MessageUtils;
import org.dalmatian.common.core.utils.SolonUtils;
import org.dalmatian.common.core.utils.StringUtils;
import org.dalmatian.common.core.utils.ValidatorUtils;
import org.dalmatian.common.core.utils.reflect.ReflectUtils;

import org.dalmatian.common.encrypt.annotation.ApiEncrypt;
import org.dalmatian.common.rateLimiter.annotation.RateLimiter;
import org.dalmatian.common.rateLimiter.enums.LimitType;
import org.dalmatian.common.redis.utils.RedisUtils;
import org.dalmatian.common.satoken.utils.LoginHelper;
import org.dalmatian.common.tenant.helper.TenantHelper;
import org.dalmatian.common.web.enums.CaptchaType;
import org.dalmatian.common.web.properties.CaptchaProperties;
import org.dalmatian.app.auth.domain.vo.CaptchaVo;
import org.dalmatian.app.auth.domain.vo.LoginTenantVo;
import org.dalmatian.app.auth.domain.vo.LoginVo;
import org.dalmatian.app.auth.domain.vo.TenantListVo;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Path;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.expression.snel.SnEL;


/**
 * 认证
 *
 * @author Lion Li
 */
@Slf4j
@SaIgnore
@RequiredArgsConstructor
@Controller
@Mapping("/auth")
public class AuthController {


    private final SysLoginService loginService;
    private final SysRegisterService registerService;
    private final ISysConfigService configService;
    private final ISysTenantService tenantService;
    private final ISysSocialService socialUserService;
    private final ISysClientService clientService;
    private ScheduledExecutorService scheduledExecutorService;
    @Inject
    private CaptchaProperties captchaProperties;

    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @Post
    @Mapping("/login")
    @SaIgnore
    @ApiEncrypt(response = true)
    public R<LoginVo> login(@Body String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        SysClientVo client = clientService.queryByClientId(clientId);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!SystemConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        loginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, client, grantType);

        Long userId = LoginHelper.getUserId();
        return R.ok(loginVo);
    }


    /**
     * 生成验证码
     */
    @Get
    @Mapping("/code")
    @SaIgnore
    public R<CaptchaVo> getCode() {
        boolean captchaEnabled = captchaProperties.getEnable();
        if (!captchaEnabled) {
            CaptchaVo captchaVo = new CaptchaVo();
            captchaVo.setCaptchaEnabled(false);
            return R.ok(captchaVo);
        }
        return R.ok(SolonUtils.getAopProxy(this).getCodeImpl());
    }

    @RateLimiter(time = 60, count = 10, limitType = LimitType.IP)
    public CaptchaVo getCodeImpl() {
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        CaptchaType captchaType = captchaProperties.getType();
        boolean isMath = CaptchaType.MATH == captchaType;
        Integer length =
            isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
        CodeGenerator codeGenerator = ReflectUtils.newInstance(captchaType.getClazz(), length);
        AbstractCaptcha captcha = new CircleCaptcha(100, 50);
        captcha.setGenerator(codeGenerator);
        captcha.createCode();
        // 如果是数学验证码，使用SpEL表达式处理验证码结果
        String code = captcha.getCode();
        if (isMath) {
            code = StringUtils.remove(code, "=").replaceAll("([0-9])([+\\-*/])", "$1 $2");
            code = String.valueOf(SnEL.eval(code));
        }
        RedisUtils.setCacheObject(verifyKey, code,
            Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        CaptchaVo captchaVo = new CaptchaVo();
        captchaVo.setUuid(uuid);
        captchaVo.setImg(captcha.getImageBase64());
        return captchaVo;
    }

    /**
     * 取消授权(需要token)
     *
     * @param socialId socialId
     */
    @Mapping(method = MethodType.DELETE, value = "/unlock/{socialId}")
    public R<Void> unlockSocial(@Path("socialId") Long socialId) {
        // 校验token
        StpUtil.checkLogin();
        Boolean rows = socialUserService.deleteWithValidById(socialId);
        return rows ? R.ok() : R.fail("取消授权失败");
    }


    /**
     * 退出登录
     */
    @Post
    @Mapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

//    /**
//     * 用户注册
//     */
//    @ApiEncrypt
//    @PostMapping("/register")
//    public R<Void> register(@Validated @RequestBody RegisterBody user) {
//        if (!configService.selectRegisterEnabled(user.getTenantId())) {
//            return R.fail("当前系统没有开启注册功能！");
//        }
//        registerService.register(user);
//        return R.ok();
//    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @Get
    @Mapping("/tenant/list")
    public R<LoginTenantVo> tenantList() throws Exception {
        // 返回对象
        LoginTenantVo result = new LoginTenantVo();
        boolean enable = TenantHelper.isEnable();
        result.setTenantEnabled(enable);
        // 如果未开启租户这直接返回
        if (!enable) {
            return R.ok(result);
        }

        List<SysTenantVo> tenantList = tenantService.queryList(new SysTenantBo());
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        try {
            // 如果只超管返回所有租户
            if (LoginHelper.isSuperAdmin()) {
                result.setVoList(voList);
                return R.ok(result);
            }
        } catch (NotLoginException ignored) {
        }

//        // 获取域名
//        String host;
//        String referer = request.getHeader("referer");
//        if (StringUtils.isNotBlank(referer)) {
//            // 这里从referer中取值是为了本地使用hosts添加虚拟域名，方便本地环境调试
//            host = referer.split("//")[1].split("/")[0];
//        } else {
//            host = new URL(request.getRequestURL().toString()).getHost();
//        }
        // 根据域名进行筛选
        List<TenantListVo> list = voList;
        result.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        return R.ok(result);
    }

}
